package com.corffen.design.singleton;

import java.util.HashMap;

public class RegisterSystemService {

    private static int sServiceCacheSize;
    private static HashMap<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCH = new HashMap<>();
    public static int init = 0;

    static {
        registerService(ContextImpl.LAYOUT, new CacheServiceFetcher<LayoutInflate>() {
            @Override
            public LayoutInflate createService(ContextImpl context) {
                return new LayoutInflate(context);
            }
        });

        registerService(ContextImpl.WINDOW, new CacheServiceFetcher<Window>() {
            @Override
            public Window createService(ContextImpl context) {
                return new Window(context);
            }
        });
    }

    private static <T> void registerService(String name, ServiceFetcher<T> serviceFetcher) {
        SYSTEM_SERVICE_FETCH.put(name, serviceFetcher);
    }

    public static Object getSystemService(ContextImpl context, String name) {
        ServiceFetcher<?> serviceFetcher = SYSTEM_SERVICE_FETCH.get(name);
        return serviceFetcher != null ? serviceFetcher.getService(context) : null;
    }

    public static Object[] createServiceCache() {
        return new Object[sServiceCacheSize];
    }

    static interface ServiceFetcher<T> {
        T getService(ContextImpl context);
    }

    static abstract class CacheServiceFetcher<T> implements ServiceFetcher<T> {

        private final int mCacheIndex;

        public CacheServiceFetcher() {
            mCacheIndex = sServiceCacheSize++;
        }

        @Override
        public T getService(ContextImpl context) {
            final Object[] cache = context.mServiceCache;
            T service = (T) cache[mCacheIndex];
            if (service != null) {
                return service;
            }
            service = createService(context);
            cache[mCacheIndex] = service;
            return service;
        }

        public abstract T createService(ContextImpl context);
    }

}
